/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jxta;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryListener;
import net.jxta.discovery.DiscoveryService;
import utilidades.ConsultaAdvertisement;

/**
 *
 * @author kastillo
 */
public class PublicarConsultas implements DiscoveryListener, Runnable {
    private static DiscoveryService discovery;
    private final long waittime;
    private final long expiration;
    private final long lifetime;
    private final byte tmpTotalEspera;
    private final ConsultaAdvertisement adv;


    PublicarConsultas(DiscoveryService discovery2,ConsultaAdvertisement queryAdv) {
        discovery = discovery2;
       
        this.waittime = 60 * 2 * 1000L;
        this.expiration = 60 * 2 * 1000L;
        this.lifetime = 5 * 1000L;
        this.tmpTotalEspera = Byte.MAX_VALUE;
        this.adv = queryAdv;

    }

 
    public void run() {
          empezar();
    }

   public void discoveryEvent(DiscoveryEvent de) {
       System.out.println("==========================EVENTO DE PUBLICAR CONSULTAS=====================================");
        throw new UnsupportedOperationException("Not supported yet.");
    }

    private void empezar() {
          long tmpTermino = System.currentTimeMillis() + tmpTotalEspera;
        boolean debeContinuar = true;

       while (debeContinuar)
        {
            try {
                //PipeAdvertisement pipeAdv = getPipeAdvertisement();
                // publish the advertisement with a lifetime of 2 mintutes
                System.out.println("Publishing the following advertisement with lifetime :" + lifetime + " expiration :" + expiration);
                System.out.println("el Advert"+adv);
                discovery.publish(adv, lifetime, expiration);
                discovery.remotePublish(adv, expiration);
                System.out.println("Sleeping for :" + waittime);
                Thread.sleep(waittime);
                long tmpActual = System.currentTimeMillis();
                if (tmpActual >= tmpTermino) {
                    debeContinuar = false;
                }
            } catch (IOException ex) {
                Logger.getLogger(PublicarConsultas.class.getName()).log(Level.SEVERE, null, ex);
                                System.err.println("Error de entrada y salida");
            } catch (InterruptedException ex) {
                Logger.getLogger(PublicarConsultas.class.getName()).
                        log(Level.INFO, "Me sacaron de mi trabajo", ex);
                return;
            }
        }
    }

}
